package com.fcwy.puzzle;import java.util.ArrayList;import java.util.List;import java.util.Random;import java.util.Timer;import java.util.TimerTask;import android.annotation.SuppressLint;import android.app.Activity;import android.content.Intent;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.graphics.drawable.Drawable;import android.net.Uri;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.view.Gravity;import android.view.MotionEvent;import android.view.View;import android.view.View.OnClickListener;import android.view.View.OnTouchListener;import android.widget.GridView;import android.widget.ImageButton;import android.widget.ImageView;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast;import com.fcwy.puzzle.adapter.GridItemsAdapter;import com.fcwy.puzzle.domain.ItemBean;import com.fcwy.puzzle.utils.AppConstant;import com.fcwy.puzzle.utils.GameUtil;import com.fcwy.puzzle.utils.HImage;import com.fcwy.puzzle.utils.HLog;import com.fcwy.puzzle.utils.HToast;import com.fcwy.puzzle.utils.ImageLoaderUtil;import com.fcwy.puzzle.utils.ImageUtil;import com.fcwy.puzzle.utils.MD5;import com.fcwy.puzzle.utils.PathUtil;import com.fcwy.puzzle.utils.ScreenUtil;import com.fcwy.puzzle.view.PopupWindowBrowse;import com.fcwy.puzzle.view.PopupWindowBrowse.CheckboxClickListener;import com.umeng.analytics.MobclickAgent;import com.umeng.update.UmengUpdateAgent;import com.umeng.update.UmengUpdateListener;import com.umeng.update.UpdateResponse;import com.umeng.update.UpdateStatus;public class MainActivity extends Activity implements OnClickListener ,OnTouchListener{ private Bitmap picSelected; // 拼图完成时显示的最后一个图片 public static Bitmap lastBitmap; // PuzzlePanel private GridView gv_puzzle_main_detail; private int resId; private String picPath; private ImageView imageView; // Button private ImageButton btnBack; private ImageButton btn_refresh; private ImageButton btn_select; private ImageButton btn_local; private ImageButton btnRestart; // 显示步数 private TextView tv_puzzle_main_counts; // 计时器 private TextView tv_Timer; // 切图后的图片 private List<Bitmap> bitmapItemLists = new ArrayList<Bitmap>(); // GridView适配器 private GridItemsAdapter adapter; // 设置为N*N显示 public static int type = 4; // Flag 是否已显示原图 private boolean isShowImg; // 步数显示 public static int countIndex = 0; // 计时显示 public static int timerIndex = 0; // 计时器类 private Timer timer; private int[][] photoMap=null; private long mLastBackPress;private static final long mBackPressThreshold = 3000;private static final int SELECT_PIC_BY_PICK_PHOTO = 1;private Toast pressBackToast; /** * UI更新Handler */private int autoIdx=0;private final int photoLength=56;private ImageView iv_photo;private PopupWindowBrowse browseWindow;private LinearLayout rootLayout;private String selectPath=null;private int selectPos=0; private Handler handler = new Handler() {@Overridepublic void handleMessage(Message msg) { switch (msg.what) { case 1:// 更新计时器timerIndex ;tv_Timer.setText(GameUtil.timeParser(timerIndex));break; default:break; }} }; /** * 计时器线程 */ private TimerTask timerTask; @SuppressLint("ShowToast")@Override protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);// 选择默认图片还是自定义图片resId = R.drawable.photo;// 对图片处理pressBackToast = Toast.makeText(getApplicationContext(),"再按一次退出游戏", Toast.LENGTH_SHORT);// 初始化ViewsinitViews();// 获取选择的图片initPuzzlePhoto();// 生成游戏数据generateGame();// GridView点击事件//gv_puzzle_main_detail.setOnItemClickListener(new OnItemClickListener() {//// @Override// public void onItemClick(AdapterView<?> arg0, View view, int position, long arg3) {// doItemSelect(position);// }//});gv_puzzle_main_detail.setOnTouchListener(this);// 返回按钮点击事件btnBack.setOnClickListener(this);btn_refresh.setOnClickListener(this);// 显示原图按钮点击事件//btnImage.setOnClickListener(this);// 重置按钮点击事件btnRestart.setOnClickListener(this);btn_select.setOnClickListener(this);btn_local.setOnClickListener(this);iv_photo.setOnClickListener(this);//checkAppUpdate(); } /** * Button点击事件 */ @Override public void onClick(View v) {switch (v.getId()) {//// 返回按钮点击事件case R.id.btn_back: finish(); break;//// 显示原图按钮点击事件//case R.id.btn_puzzle_main_img:// Animation animShow = AnimationUtils.loadAnimation(PuzzleMain.this, R.anim.image_show_anim);// Animation animHide = AnimationUtils.loadAnimation(PuzzleMain.this, R.anim.image_hide_anim);// if (isShowImg) {//imageView.startAnimation(animHide);//imageView.setVisibility(View.GONE);//isShowImg = false;// } else {//imageView.startAnimation(animShow);//imageView.setVisibility(View.VISIBLE);//isShowImg = true;// }// break;//// 重置按钮点击事件case R.id.btn_start:case R.id.btn_refresh:initPuzzlePhoto(); cleanConfig(); generateGame(); recreateData(); // 通知GridView更改UI tv_puzzle_main_counts.setText("" countIndex); adapter.notifyDataSetChanged(); gv_puzzle_main_detail.setEnabled(true); break;case R.id.iv_photo:List<String> listUrl=new ArrayList<String>();listUrl.add(selectPath);browseWindow = new PopupWindowBrowse(MainActivity.this,listUrl,0,picSelected,null);browseWindow.showAtLocation(rootLayout,Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);break;case R.id.btn_select:final List<String> listPhoto=new ArrayList<String>();CheckboxClickListener listner=new CheckboxClickListener() {@Overridepublic void onConfirm(int position) {// TODO Auto-generated method stubselectPos=position;selectPath=PathUtil.CACHE_IMG MD5.md5(listPhoto.get(position)); Bitmap picSelectedTemp=HImage.getLocalThumbImg(selectPath, 720, 1280); if(picSelectedTemp==null) { picSelectedTemp=BitmapFactory.decodeResource(getResources(), resId); } iv_photo.setImageBitmap(picSelectedTemp); handlerImage(picSelectedTemp);cleanConfig(); generateGame(); recreateData(); // 通知GridView更改UI tv_puzzle_main_counts.setText("" countIndex); adapter.notifyDataSetChanged(); gv_puzzle_main_detail.setEnabled(true);}};browseWindow = new PopupWindowBrowse(MainActivity.this,listPhoto,selectPos,null,listner);browseWindow.showAtLocation(rootLayout,Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);break;case R.id.btn_local://本地相册pickPhoto();break;} } private void pickPhoto() {// TODO Auto-generated method stubIntent choosePictureIntent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);startActivityForResult(choosePictureIntent, SELECT_PIC_BY_PICK_PHOTO);}private void initPuzzlePhoto() {//int id=new Random().nextInt(photoLength-2) 2;//selectPos=id-2;//selectPath=PathUtil.CACHE_IMG MD5.md5(AppConstant.BASE_PHOTO_URL id ".jpg");Bitmap picSelectedTemp=null;//HImage.getLocalBitMap(MainActivity.this, selectPath, false);if(picSelectedTemp==null) {picSelectedTemp=BitmapFactory.decodeResource(getResources(), resId);}iv_photo.setImageBitmap(picSelectedTemp);handlerImage(picSelectedTemp);} private void generateGame() {// 切图 获取初始拼图数据 正常顺序new ImageUtil().createInitBitmaps(type, picSelected, MainActivity.this);// 生成随机数据GameUtil.getPuzzleGenerator();// 获取Bitmap集合//int length=GameUtil.itemBeans.size();photoMap=new int[type][type];for (ItemBean temp : GameUtil.itemBeans) { bitmapItemLists.add(temp.getBitmap()); }for(int y=0;y<type;y ) {for(int x=0;x<type;x ) {photoMap[x][y]=x y*type;}}autoIdx = photoMap.length - 1;// 数据适配器adapter = new GridItemsAdapter(this, bitmapItemLists);gv_puzzle_main_detail.setAdapter(adapter);// 启用计时器timer = new Timer(true);// 计时器线程timerTask = new TimerTask() { @Override public void run() { handler.sendEmptyMessage(1); }};// 每1000ms执行 延迟0stimer.schedule(timerTask, 0, 1000); } public void checkAppUpdate() {//检查更新UmengUpdateAgent.setUpdateOnlyWifi(false);UmengUpdateAgent.setUpdateListener(new UmengUpdateListener() {@Overridepublic void onUpdateReturned(int updateStatus,UpdateResponse updateInfo) {switch (updateStatus) {case UpdateStatus.Yes: // has updateUmengUpdateAgent.showUpdateDialog(MainActivity.this, updateInfo);break;case UpdateStatus.Timeout: // time out//HToast.showShortText(MainActivity.this, "网络连接超时");break;}}});UmengUpdateAgent.update(MainActivity.this);} /** * 添加显示原图的View */ private void addImgView() {//RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.rl_puzzle_main_main_layout);//imageView = new ImageView(PuzzleMain.this);//imageView.setImageBitmap(picSelected);//int x = (int) (picSelected.getWidth() * 0.9F);//int y = (int) (picSelected.getHeight() * 0.9F);//LayoutParams params = new LayoutParams(x, y);//params.addRule(RelativeLayout.CENTER_IN_PARENT);//imageView.setLayoutParams(params);//relativeLayout.addView(imageView);//imageView.setVisibility(View.GONE); } /** * 返回时调用 */ @Override protected void onStop() {super.onStop();// 清空相关参数设置cleanConfig(); } /** * 清空相关参数设置 */ private void cleanConfig() {// 清空相关参数设置GameUtil.itemBeans.clear();// 停止计时器timer.cancel();timerTask.cancel();countIndex = 0;timerIndex = 0;// 清除拍摄的照片if (picPath != null) { // 删除照片// File file = new File(MainActivity.TEMP_IMAGE_PATH);// if (file.exists()) {//file.delete();// }} } /** * 重新获取图片 */ private void recreateData() {bitmapItemLists.clear();for (ItemBean temp : GameUtil.itemBeans) { bitmapItemLists.add(temp.getBitmap());} } /** * 对图片处理 自适应大小 * * @param bitmap */ private void handlerImage(Bitmap bitmap) {// 将图片放大到固定尺寸int screenWidth = ScreenUtil.getScreenSize(this).widthPixels;int screenHeigt = ScreenUtil.getScreenSize(this).heightPixels;picSelected = new ImageUtil().resizeBitmap(screenWidth * 0.8f, screenHeigt * 0.6f, bitmap); } /** * 初始化Views */ private void initViews() {// Button btnBack = (ImageButton) findViewById(R.id.btn_back);//btnImage = (ImageButton) findViewById(R.id.btn_puzzle_main_img);btn_refresh = (ImageButton) findViewById(R.id.btn_refresh);btnRestart = (ImageButton) findViewById(R.id.btn_start);btn_select = (ImageButton) findViewById(R.id.btn_select);btn_local = (ImageButton) findViewById(R.id.btn_local);// Flag 是否已显示原图isShowImg = false;rootLayout=(LinearLayout)findViewById(R.id.puzzle_main_main_layout);// GVgv_puzzle_main_detail = (GridView) findViewById(R.id.gv_puzzle_main_detail);// 设置为N*N显示gv_puzzle_main_detail.setNumColumns(type);// TV步数tv_puzzle_main_counts = (TextView) findViewById(R.id.tv_step);tv_puzzle_main_counts.setText("" countIndex);// TV计时器tv_Timer = (TextView) findViewById(R.id.tv_time);tv_Timer.setText("0秒");iv_photo= (ImageView) findViewById(R.id.iv_photo);//ImageView iv_temp = (ImageView) findViewById(R.id.iv_temp);//for(int i=2;i<=photoLength;i ) {//String url=AppConstant.BASE_PHOTO_URL i ".jpg";//Drawable defaultDraw= getResources().getDrawable(R.drawable.blank);//ImageLoaderUtil.loadImageAsync("MainActivity",iv_temp, url, PathUtil.CACHE_IMG, // defaultDraw, 600); //}// 添加显示原图的ViewaddImgView(); } private float startX,startY,offsetX,offsetY,lastX,lastY;@Overridepublic boolean onTouch(View v, MotionEvent event) {switch (event.getAction()) {case MotionEvent.ACTION_DOWN:startX = event.getX();startY = event.getY();lastX=(int)event.getRawX();lastY=(int)event.getRawY();break;case MotionEvent.ACTION_UP:offsetX = event.getX()-startX;offsetY = event.getY()-startY;// 若 up 与 down 都为同一个点则认为是点击事件if(Math.abs(event.getRawX() - lastX) <= 1 && Math.abs(event.getRawY() - lastY) <= 1){}if (Math.abs(offsetX)>Math.abs(offsetY)) {if (offsetX<-5) {//向左swipeLeft();}else if (offsetX>5) {//向右swipeRight();}}else{if (offsetY<-5) {//向上swipeUp();}else if (offsetY>5) {//向下swipeDown();}}break;}return true;}private void swipeLeft() {// 获取空格Itemint blankId = GameUtil.blankItemBean.getItemId() - 1;boolean isMove=false;for(int y=0;y<photoMap.length;y ) {for(int x=0;x<photoMap.length;x ) {int position=photoMap[x][y];if(blankId==position) {for(int x1=x;x1<photoMap.length;x1 ) {int selectPos=photoMap[x1][y];isMove=doItemSelect(selectPos);if(isMove)break;}}if(isMove)break;}if(isMove)break;}}private void swipeRight() {// 获取空格Itemint blankId = GameUtil.blankItemBean.getItemId() - 1;boolean isMove=false;for(int y=0;y<photoMap.length;y ) {for(int x=0;x<photoMap.length;x ) {int position=photoMap[x][y];if(blankId==position) {for(int x1=x;x1>=0;x1--) {int selectPos=photoMap[x1][y];isMove=doItemSelect(selectPos);if(isMove)break;}}if(isMove)break;}if(isMove)break;}}private void swipeUp() {// 获取空格Itemint blankId = GameUtil.blankItemBean.getItemId() - 1;boolean isMove=false;for(int x=0;x<photoMap.length;x ) {for(int y=0;y<photoMap.length;y ) {int position=photoMap[x][y];if(blankId==position) {for(int y1=y;y1<photoMap.length;y1 ) {int selectPos=photoMap[x][y1];isMove=doItemSelect(selectPos);if(isMove)break;}}if(isMove)break;}if(isMove)break;}}private void swipeDown() {// 获取空格Itemint blankId = GameUtil.blankItemBean.getItemId() - 1;boolean isMove=false;for(int x=0;x<photoMap.length;x ) {for(int y=0;y<photoMap.length;y ) {int position=photoMap[x][y];if(blankId==position) {for(int y1=y;y1>=0;y1--) {int selectPos=photoMap[x][y1];isMove=doItemSelect(selectPos);if(isMove)break;}}if(isMove)break;}if(isMove)break;}}private boolean doItemSelect(int position) {boolean isMove=false;// 判断是否可移动if (GameUtil.isMoveable(position)) { // 交换点击Item与空格的位置 GameUtil.swapItems(GameUtil.itemBeans.get(position), GameUtil.blankItemBean); // 重新获取图片 recreateData(); // 通知GridView更改UI adapter.notifyDataSetChanged(); // 更新步数 countIndex ;tv_puzzle_main_counts.setText("" countIndex); isMove=true; // 判断是否成功 if (GameUtil.isSuccess()) { // 将最后一张图显示完整 recreateData(); bitmapItemLists.remove(type * type - 1); bitmapItemLists.add(lastBitmap); // 通知GridView更改UI adapter.notifyDataSetChanged(); Toast.makeText(MainActivity.this, "恭喜,拼图成功!", Toast.LENGTH_LONG).show(); gv_puzzle_main_detail.setEnabled(false); timer.cancel(); timerTask.cancel(); }}return isMove;}@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {// TODO Auto-generated method stubsuper.onActivityResult(requestCode, resultCode, data);if (resultCode == RESULT_OK) { if(requestCode==SELECT_PIC_BY_PICK_PHOTO) {//选择图库图片结果Uri photoUri = data.getData();selectPath = HImage.getPicPathFromUri(photoUri, this); Bitmap picSelectedTemp=HImage.getLocalThumbImg(selectPath, 720, 1280); if(picSelectedTemp==null) { picSelectedTemp=BitmapFactory.decodeResource(getResources(), resId); } iv_photo.setImageBitmap(picSelectedTemp); handlerImage(picSelectedTemp); cleanConfig(); generateGame(); recreateData(); // 通知GridView更改UI tv_puzzle_main_counts.setText("" countIndex); adapter.notifyDataSetChanged(); gv_puzzle_main_detail.setEnabled(true);}}}@Override public void onResume() { super.onResume(); MobclickAgent.onResume(this); //统计时长}@Override public void onPause() { super.onPause(); MobclickAgent.onPause(this);}@Overrideprotected void onDestroy() {// TODO Auto-generated method stubsuper.onDestroy();if(timer!=null) {timer.cancel();timerTask.cancel();}}@Overridepublic void onBackPressed() { long currentTime = System.currentTimeMillis(); if (Math.abs(currentTime - mLastBackPress) > mBackPressThreshold) { pressBackToast.show(); mLastBackPress = currentTime; } else { pressBackToast.cancel(); super.onBackPressed(); }}}
下载android 拼图游戏 源码下载用户还喜欢
- 18480 文章数
- 500万+ 热度
作者专栏
编辑推荐
- 淡抹u2引擎,修复内容较多,物有所值
- 界域传说·经典巨作=传世单机(一键安装)
- 丸子版本(175个传世版本大集合)
- GS版本:神话公益服务端+客户端
- 图片放大工具(放大图片不模糊)
- 剪映无限制VIP版
- 传奇世界客户端下载器,史上最全传世客户端
- 传世GS20220920商业引擎注册+登录配置器 解压密码是1
- U2官方排行榜游戏网关 支持元神,支持传家宝
- GS开战传世客户端+服务端
- (淡漠夕阳)u2引擎合区工具
- 传世GS引擎消除“你的游戏客户端版本号过旧,请及时更新”提示
- 传世一机多区双线路配置器--免密码版本
- 传世凤凰登陆器劫持修复软件
- SQLite3 for Navicat
- 传奇世界npc对话框编辑工具
- 传世GS落霞铭文服务器端
- gs_20210409引擎包+注册机(无限制)
- 传奇世界NPC对话封包查看器[支持时长版和极速版]
- 彩虹引擎传世脚本编辑工具1.7版来了,支持函数脚本翻译
评论